package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.AddressClient;
import com.hmall.common.client.SearchClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.interceptor.Admininterceptor;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private SearchClient searchClient;

    @Autowired
    private AddressClient addressClient;


    @Override
    public Long createOrder(OrderDto dto) {
        Item item = searchClient.getById(dto.getItemId());

        if(item.getStock()<dto.getNum()){
            throw new RuntimeException("库存不足创建订单失败");
        }

        Integer totalFee = Math.toIntExact(dto.getNum() * item.getPrice());
        //设置当前创建订单人的id，userId
        Long userId = Admininterceptor.getUserId();
        Order order = Order.builder().totalFee(Long.valueOf(totalFee))
                .status(1).createTime(Timestamp.valueOf(LocalDateTime.now()))
                .paymentType(dto.getPaymentType()).userId(2L).userId(userId).build();
        orderMapper.insert(order);

        OrderDetail orderDetail = OrderDetail.builder().orderId(order.getId())
                .itemId(dto.getItemId()).num(dto.getNum())
                .title(item.getName()).price(item.getPrice())
                .spec(item.getSpec()).image(item.getImage()).createTime(Timestamp.valueOf(LocalDateTime.now()))
                .build();
        orderDetailMapper.insert(orderDetail);

        Address address = addressClient.findAddressById(dto.getAddressId());

        OrderLogistics orderLogistics = OrderLogistics.builder().contact(address.getContact())
                .phone(address.getMobile()).province(address.getProvince())
                .city(address.getCity()).town(address.getTown()).street(address.getStreet())
                .createTime(Timestamp.valueOf(LocalDateTime.now())).build();
        orderLogisticsMapper.insert(orderLogistics);

        searchClient.changes(item.getId(),dto.getNum());

        return order.getId();
    }
}

